import { _decorator, CCInteger, CCString, Component, Enum, sys, view } from 'cc';
import { ResMgr } from '../manager/ResMgr';
import { UIMgr } from '../manager/UIMgr';
import { EnvType, GameConfig, REPORT_API_KEY_RELEASE, REPORT_API_KEY_TEST, UIConfig, UIID } from '../data/GameConfig';
import { Prefab } from 'cc';
import HotUpdateMgr from '../manager/HotUpdateMgr';
import { game } from 'cc';
import { Game } from 'cc';
import NativeHelper from '../comm/NativeHelper';
import { EventReport } from '../net/EventReport';
import LocalValues from '../data/LocalValues';
import { XUtils } from '../comm/XUtils';
import { ResolutionPolicy } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('Launch')
export class Launch extends Component {
    
    @property({ serializable: true })
    private _envType: EnvType = EnvType.Test;
    @property({ serializable: true })
    private _versionCode: number = 1;
    @property({ serializable: true })
    private _version: string = '1.0.0';
    @property({ group: { name: 'Config' }, displayName: "Env", type: Enum(EnvType) })
    private set envType(value: EnvType) {
        this._envType = value;
    }
    private get envType(): EnvType {
        return this._envType
    }
    @property({ group: { name: 'Config' }, displayName: "VersionCode", type: CCInteger })
    private set versionCode(value: number) {
        this._versionCode = value;
    }
    private get versionCode(): number {
        return this._versionCode;
    }
    @property({ group: { name: 'Config' }, displayName: "Version", type: CCString })
    private set version(value: string) {
        this._version = value;
    }
    private get version(): string {
        return this._version;
    }


    private _hideTime = 0;
    protected onLoad(): void {
        this.fitScreen();
        this.initConfig();
        // InsLoggerModel.start();//日志功能 最早启动，尽早监听
        game.frameRate = 60;
        game.on(Game.EVENT_SHOW, this.onGameShow, this);
        game.on(Game.EVENT_HIDE, this.onGameHide, this);
        // 首次启动
        if (!LocalValues.getUserData()) {
            EventReport.app_first_open();
        }
        // 启动应用
        EventReport.app_open();
        // 本地资源检查
        EventReport.local_resource_check_start();
        // 本地资源检查完成
        EventReport.local_resource_check_complete();
        // 热更资源检查
        EventReport.hot_update_check_start();
        // 热更资源检查完成
        EventReport.hot_update_check_complete();
        // 加载登录资源
        EventReport.load_login_data_start();
        // 加载登录资源完成
        EventReport.load_login_data_complete();
        // 自动登录准备工作开始
        EventReport.pre_autologin_start();
        // 自动登录准备工作完成
        EventReport.pre_autologin_complete();
    }
    private initConfig(){
        console.info('====launch====');
        console.info('envType',this.envType);
        console.info('version',this.version);
        console.info('versionCode',this.versionCode);
        GameConfig.envType = this.envType;
        GameConfig.version = this.version;
        GameConfig.versionCode = this.versionCode;
        if (this.envType == EnvType.Release) {
            GameConfig.reportApiKey = REPORT_API_KEY_RELEASE;
            GameConfig.httpUrl = 'http://solitaire.and.51chivalry.com';
        } else {
            GameConfig.reportApiKey = REPORT_API_KEY_TEST;
            GameConfig.httpUrl = 'http://solitaire.test.woohooslots.com:8080/';
        }
        NativeHelper.launchTime = XUtils.formatDateToSimple(Date.now(), 'yyyy-MM-dd HH:mm:ss');
        // 获取安全区域
        try {
            const rect = sys.getSafeAreaRect();
            GameConfig.marginBottom = rect.y * 0.5;
            GameConfig.marginTop = (view.getVisibleSize().height - rect.height - rect.y) * 0.5;
        } catch (error) {
            console.error('get SafeMargin error',error);
        }
    }
    private onGameShow() {
        // 如果后台超过1小时，重启以检查更新
        // console.log('onGameShow',Date.now() - this._hideTime);
        if (Date.now() - this._hideTime > GameConfig.backRestartTime) {
            game.restart();
        }
    }
    private onGameHide() {
        this._hideTime = Date.now();
        // console.log('onGameHide',this._hideTime);
        
    }
    start() {
        NativeHelper.init();
        HotUpdateMgr.instance.checkMainVersion();
        //初始化UI配置表
        UIMgr.instance.initUIConf(UIConfig);
        //初始化基础场景
        this.initGame();
        // //播放背景音乐
        // AudioMgr.instance.playHallBgm();
    }


    private async initUIMask(){
        return ResMgr.instance.load('prefab/comm/mask', Prefab, (err , prefab: Prefab)=>{
            if(err){
                prefab?.decRef();
                return;
            }
            prefab.addRef();
            GameConfig.UIMaskPrefab = prefab;
        })
    }


    private initGame(){
        this.initUIMask();
        this.enterApp();
    }
  
    private enterApp(){
        console.log('#### enterApp');
        UIMgr.instance.open(UIID.UILoading);
    }

    private fitScreen(){
        // 根据屏幕比例动态设置适配策略
        const screenRatio = view.getVisibleSize().height / view.getVisibleSize().width;
        if (screenRatio > 16/9) { // 手机竖屏
            // 使用宽度适配
            view.setResolutionPolicy(ResolutionPolicy.FIXED_WIDTH);
        } else { // 平板
            // 使用高度适配
            view.setResolutionPolicy(ResolutionPolicy.FIXED_HEIGHT);
        }
        // //3.8.4 bug 需要手动触发canvas-resize事件
        // view.emit('canvas-resize');
    }

    protected onDestroy(): void {
        game.off(Game.EVENT_SHOW, this.onGameShow, this);
        game.off(Game.EVENT_HIDE, this.onGameHide, this);
    }
}


